package com.dcjt.firehotcarpad.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;

import androidx.annotation.NonNull;

import com.dcjt.firehotcarpad.service.MessageService;

import java.util.List;

public class ServiceUtils {
    /**
     * @param activity 登录界面
     */

    public static void startService(@NonNull Activity activity ) {
        if (activity == null ) return;

        Intent floatButtonIntent = new Intent(activity, MessageService.class);
        if (serviceIsLive(activity, MessageService.class.getSimpleName())) {
            activity.stopService(floatButtonIntent);
        }
        activity.startService(floatButtonIntent);

    }

    public static void stopService(Activity activity) {
        try {

            Intent floatingButtonIntent = new Intent(activity, MessageService.class);
            activity.stopService(floatingButtonIntent);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public static boolean serviceIsLive(Context context, String className){


        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> serviceList = activityManager
                .getRunningServices(Integer.MAX_VALUE);

        if (!(serviceList.size() > 0)) {
            return false;
        }

        for (int i = 0; i < serviceList.size(); i++) {
            ActivityManager.RunningServiceInfo serviceInfo = serviceList.get(i);
            ComponentName serviceName = serviceInfo.service;

            if (serviceName.getClassName().equals(className)) {
                return true;
            }
        }
        return false;

    }

}
